// src/routes/index.ts


import { type Express, Router } from 'express'
import WebGamesRoutes from './web-games'
import BugManagerRoutes from './bug-manager'
import BilibiliRoutes from './bilibili'

// 路由配置接口
interface RouterConf {
  path: string,
  router: Router,
}

// 路由配置
const routerConf: Array<RouterConf> = []

const notFoundFunction = (request: any, response: any) => {
  response.send(``)
}

const allRoutes: Array<any> = [
  ...WebGamesRoutes,
  ...BugManagerRoutes,
  ...BilibiliRoutes,
]

function routes(app: Express) {

  for (let index = 0; index < allRoutes.length; index++) {
    if (allRoutes[index].path.indexOf('bl') == -1) {
      if (allRoutes[index].method == 'get') {
        app.get(
          allRoutes[index].path,
          async (request: any, response: any) => {
            let queryParams = request.query
            response.send(
              await new Promise<void>(async (resolve, reject) => {
                allRoutes[index].func(queryParams, resolve, response)
              })
            )
          })
      } else {
        app.post(
          allRoutes[index].path,
          async (request: any, response: any) => {
            let queryParams = request.body
            response.send(
              await new Promise<void>(async (resolve, reject) => {
                allRoutes[index].func(queryParams, resolve)
              })
            )
          })
      }
    } else {
      if (allRoutes[index].method == 'get') {
        app.get(
          allRoutes[index].path,
          async (request: any, response: any) => {
            let queryParams = request.query
            allRoutes[index].func(queryParams, response)
        })
          // allRoutes[index].func)
      } else {
        app.post(
          allRoutes[index].path,
          async (request: any, response: any) => {
            let queryParams = request.body
            response.send(
              await new Promise<void>(async (resolve, reject) => {
                allRoutes[index].func(queryParams, resolve)
              })
            )
          })
      }
    }
  }

  app.get('/', notFoundFunction)
  app.post('/', notFoundFunction)

  routerConf.forEach((conf) => app.use(conf.path, conf.router))
}

export default routes